package com.kfm.servlet;

import com.kfm.dao.UserDao;
import com.kfm.model.User;
import com.wf.captcha.utils.CaptchaUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置获取请求的流的编码
        req.setCharacterEncoding("utf-8");
        // 设置响应流的编码
        resp.setCharacterEncoding("UTF-8");
        // 设置浏览器如何去渲染响应的内容
        resp.setContentType("text/html;charset=utf-8");
        String verCode = req.getParameter("verCode");
        boolean ver = CaptchaUtil.ver(verCode, req);
        if (ver) {
            // 获取请求参数
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            // 去数据库查询用户账号密码是否正确
            User user = userDao.selectByUsernameAndPassword(username, password);
            if (user == null) {
                System.out.println("登录失败");
                resp.getWriter().write("<h3>登录失败，用户名或密码错误</h3>");
            } else {
                System.out.println("登录成功！");
                resp.getWriter().write("<h3>登录成功</h3>");
            }
        } else {
            System.out.println("验证码错误");
            resp.getWriter().write("<h3>验证码错误</h3>");
        }
    }
}
